/**
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.hq.sso.interceptor;


import com.hq.sso.utils.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 权限(Token)验证
 */
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    private Logger logger = LoggerFactory.getLogger(getClass());

    @Value("${sso.validationUrl}")
    private String validationUrl;

    @Value("${sso.serviceUrl}")
    private String serviceUrl;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession(true);

        String currentUrl = request.getRequestURL().toString();
        logger.info("currentUrl=" + currentUrl);
        logger.info("getQueryString=" + request.getQueryString());

        //从header中获取token
        String token = request.getHeader("baibaomensso");
        //如果header中不存在token，则从参数中获取token
        if (token == null) {
            token = request.getParameter("baibaomensso");
        }
        logger.info("token=" + token);

        //token为空
        if (token != null) {
            String json = HttpUtil.doGet4Json(this.validationUrl + token);
            logger.info("验证信息=" + json);
            if (json == null) {
                logger.warn("未授权,请重新登录");
                throw new Exception("未授权,请重新登录");
            }

            session.setAttribute("Account", json);

            //带token参数的请求地址，替换为不带的。
//        var dest = Request.RawUrl.Replace("baibaomensso=", "").Replace(baibaomenSso, "");
//        dest = dest[dest.Length-1] == '?' ? dest.Substring(0, dest.Length - 1) : dest;

            logger.info("回调地址=" + currentUrl);

            response.sendRedirect(currentUrl);
            return false;

        }

        //2 用户尚无本站会话，判定为未登录
        if (session.getAttribute("Account") == null) {
            //3. 跳转到SSO服务做认证
            String strBackUrl = serviceUrl + currentUrl;
            logger.info("strBackUrl=" + strBackUrl);
            response.sendRedirect(strBackUrl);
            return false;
        }

        return true;
    }
}
